import Toast from 'tdesign-miniprogram/toast/index';
import { getSchoolFromCode, getAllStudent, getSchoolFromId } from '../../../../services/students/studentData';
import { resolveStudents, rejectStudents, clearStudentsPromise } from './util';
import { getSelectedSchoolId, setStudentsList, getStudentsList, getSchoolList, getSelectedSchoolData, getSizeListHeight, getSizeListWeight, getGradesName } from '../../../../userData/userData';
const innerNameReg = '^[a-zA-Z\\d\\u4e00-\\u9fa5]+$';

Page({
  options: {
    multipleSlots: true,
  },
  externalClasses: ['theme-wrapper-class'],
  data: {
    locationState: {
      _id: 0,
      u_id: 0,
      i_id: 0,
      default: 0,
      name: '',
      height: 0,
      weight: 0,
      special: 0,
      grade: 0,
      class: "",
      bust: 0,
      waist: 0,
      hips: 0,
    },
    isEdit: false,
    sexVisible: false,
    sexValue: '',
    sexText: '选择性别',
    sexs: [
      { label: '男' },
      { label: '女' },
    ],
    schoolVisible: false,
    schoolValue: '',
    schoolText: '选择学校',
    schools: [],
    gradeVisible: false,
    gradeValue: '',
    gradeText: '选择年级',
    grades: [],
    classVisible: false,
    classValue: '',
    classText: '选择班级',
    classes: [],
    height: [
      { id: 1, label: '身高110-120cm' },
      { id: 2, label: '身高120-130cm' },
      { id: 3, label: '身高130-140cm' },
      { id: 4, label: '身高140-150cm' },
      { id: 5, label: '身高150-160cm' },
      { id: 6, label: '身高160-164cm' },
      { id: 7, label: '身高165-170cm' },
      { id: 8, label: '身高170-175cm' },
      { id: 9, label: '身高175-180cm' },
      { id: 10, label: '身高180-190cm' }
    ],
    heightValue: '',
    heightText: '选择身高',
    heightVisible: false,
    weight: [
      { id: 1, label: '体重20-24kg' },
      { id: 2, label: '体重25-29kg' },

      { id: 3, label: '体重30-34kg' },
      { id: 4, label: '体重35-40kg' },
      { id: 5, label: '体重45-50kg' },
      { id: 6, label: '体重50-54kg' },
      { id: 7, label: '体重55-64kg' },
      { id: 8, label: '体重60-69kg' },
      { id: 9, label: '体重70-75kg' },
      { id: 10, label: '体重75-85kg' }
    ],
    weightValue: '',
    weightText: '选择体重',
    weightVisible: false,
    schoolId: "",
    kindergartenVisible: false
  },
  privateData: {
    verifyTips: '',
    schoolData: '',
    grade: [
      "一",
      "二",
      "三"
    ],
    gradeMap: [],
    gradeDescMap: [],
  },
  onLoad(options) {
    const { id, schoolId } = options;
    this.setHeight(11, 0)
    this.setSizeListWeight(11, 0)
    this.init(id, schoolId);
  },
  onUnload() {
    if (!this.hasSava) {
      rejectStudents();
    }
  },
  hasSava: false,
  init(id, schoolId) {
    if (id) {
      const studentList = getStudentsList()
      studentList.forEach(element => {
        if (element._id == id) {
          this.setData({ locationState: element })
          this.setData({
            sexText: element.sex, sexValue: element.sex,
            gradeText: element.grade, gradeValue: element.grade,
            classText: element.class, classValue: element.class,
            schoolId: element.i_id,
            heightValue: element.height, heightText: element.height,
            weightValue: element.weight, weightText: element.weight,
          })
          this.getSchoolsDetail(element.i_id)
          this.getGradeDetail(element.i_id)
        }
      });
    }
    else {

      this.getSchoolsDetail(schoolId)
      this.getGradeDetail(schoolId || getSelectedSchoolId())
    }
  },
  setHeight(size, start) {
    this.setData({ height: getSizeListHeight(size, start) })
  },
  setSizeListWeight(size, start) {
    this.setData({ weight: getSizeListWeight(size, start) })
  },
  getSchoolsDetail(id) {

    // getSchoolFromId(id || getSelectedSchoolId()).then((schoolData) => {
    const allSchoolList = getSchoolList()
    const { code, name } = allSchoolList[id || getSelectedSchoolId()]
    let tempSchool = [];
    tempSchool.push({ label: name, id: code })
    schoolValue:
    this.setData({
      schools: tempSchool,
      schoolValue: code,
      schoolText: name,
      schoolId: id
    })
    // })


  },
  getGradeDetail(id) {
    const schoolDate = getSchoolList()
    let gradeString = ""
    if (id) {
      gradeString = schoolDate[id].grade
    }
    else {
      gradeString = getSelectedSchoolData().grade
    }
    var gradeCount = this.getSplitGradeClass(gradeString)
    if (gradeCount[0].value <= 9) {
      this.setData({
        kindergartenVisible: true
      })
    }
    else {
      this.setData({
        kindergartenVisible: false
      })
    }
    this.setData({
      grades: gradeCount,
    })
    let grade = this.data.gradeValue != "" ? this.privateData.gradeDescMap[this.data.gradeValue] : gradeCount[0].value;
    this.setData(
      {
        classes: this.getClassDesc(grade)
      }
    )
  },
  getGradeDesc(level) {
    return getGradesName(level)
  },
  onInputValue(e) {
    const { item } = e.currentTarget.dataset;
    const { value = '' } = e.detail;
    this.setData(
      {
        [`locationState.${item}`]: value,
      },
    );

  },
  //选择班级
  onGradePicker() {
    this.setData({ gradeVisible: true });
  },
  //选择班级
  onClassPicker() {
    if (!this.data.gradeValue || this.data.gradeValue == '') {
      Toast({
        context: this,
        selector: '#t-toast',
        message: "请先选择年级",
        icon: '',
        duration: 1000,
      });
      return
    }
    this.setData({ classVisible: true });
  },
  onHeightPicker() {
    this.setData({ heightVisible: true });
  },
  onWeightPicker() {
    this.setData({ weightVisible: true });
  },
  onClassColumnChange(e) {

  },
  onPickerClassChange(e) {
    const { key } = e.currentTarget.dataset;
    const { label, value } = e.detail;
    if (key == "grade") {
      if (label[0] != this.data[`${key}Value`]) {
        this.setData({
          classValue: '',
          classText: "选择班级"
        })
      }
    }
    this.setData({
      [`${key}Visible`]: false,
      [`${key}Value`]: label[0],
      [`${key}Text`]: label.join(' '),
    });
    if (key == "grade") {
      this.setData(
        {
          classes: this.getClassDesc(value[0])
        }
      )
      if (value[0] <= 9) {
        this.setHeight(3, 0)
        this.setSizeListWeight(3, 0)
        return
      }
      if (value[0] <= 15) {
        this.setHeight(7, 0)
        this.setSizeListWeight(8, 0)
        return
      }
      if (value[0] > 18) {
        this.setHeight(11, 3)
        this.setSizeListWeight(11, 3)
        return
      }
      this.setHeight(11, 0)
      this.setSizeListWeight(11, 0)

    }
  },
  onPickerClassCancel(e) {
    const { key } = e.currentTarget.dataset;
    console.log('picker cancel', e.detail);
    this.setData({
      [`${key}Visible`]: false,
    });
  },

  //选择性别/学校
  onColumnChange(e) {
    console.log('picker pick:', e);
  },
  onPickerChange(e) {
    const { key } = e.currentTarget.dataset;
    const { label } = e.detail;
    this.setData({
      [`${key}Visible`]: false,
      [`${key}Value`]: label[0],
      [`${key}Text`]: label.join(' '),
    });
  },

  onPickerCancel(e) {
    const { key } = e.currentTarget.dataset;
    console.log('picker cancel', e.detail);
    this.setData({
      [`${key}Visible`]: false,
    });
  },

  onSexPicker() {
    this.setData({ sexVisible: true });
  },
  onSchoolPicker() {
    this.setData({ schoolVisible: true });
  },

  onClassPickerChange(e) {
    const { key } = e.currentTarget.dataset;
    const { label } = e.detail;

    console.log('picker change:', e.detail);
    this.setData({
      sexVisible: false,
      sexValue: label[0],
      sexText: label.join(' '),
    });
  },

  onClassPickerCancel(e) {
    console.log('picker cancel', e.detail);
    this.setData({
      sexVisible: false,
    });
  },
  onCheckDefaultStudents({ detail }) {
    const { value } = detail;
    this.setData({
      'locationState.isDefault': value,
    });
  },
  onCheckSpecialStudents({ detail }) {
    const { value } = detail;
    this.setData({
      ['locationState.special']: value,
    });
  },


  onVerifyInputLegal() {
    const data = this.data
    const prefixNameReg = String(this.properties.nameReg || innerNameReg);
    const nameRegExp = new RegExp(prefixNameReg);
    if (!this.data.kindergartenVisible && (!data.classValue || data.classValue == '')) {
      return {
        isLegal: false,
        tips: '请选择班级',
      };
    }
    if (data.locationState._id != 0) {
      return {
        isLegal: true,
        tips: '添加成功',
      };
    }
    if (!data.locationState.name || !data.locationState.name.trim()) {
      return {
        isLegal: false,
        tips: '请填写学生姓名',
      };
    }
    if (!nameRegExp.test(data.locationState.name)) {
      return {
        isLegal: false,
        tips: '学生姓名仅支持输入中文、英文（区分大小写）、数字',
      };
    }
    if (!data.schoolValue || data.schoolValue == '') {
      return {
        isLegal: false,
        tips: '请选择学校',
      };
    }
    if (!data.gradeValue || data.gradeValue == '') {
      return {
        isLegal: false,
        tips: '请选择年级',
      };
    }

    if (!data.sexValue || data.sexValue == '') {
      return {
        isLegal: false,
        tips: '请选择性别',
      };
    }
    if (!data.weightValue || data.weightValue == '') {
      return {
        isLegal: false,
        tips: '请选择身高体重',
      };
    }
    if (!data.heightValue || data.heightValue == '') {
      return {
        isLegal: false,
        tips: '请选择身高身高',
      };
    }
    if (data.locationState.special == 1 && (data.locationState.bust == 0 || data.locationState.waist == 0 || data.locationState.hips == 0)) {
      return {
        isLegal: false,
        tips: '请填写特体数据',
      };
    }
    return {
      isLegal: true,
      tips: '添加成功',
    };
  },


  formSubmit() {
    if (this.hasSava) {
      return
    }
    const { isLegal, tips } = this.onVerifyInputLegal();
    const { locationState } = this.data
    console.log(this.privateData.verifyTips, tips)
    this.privateData.verifyTips = tips;
    if (!isLegal) {
      Toast({
        context: this,
        selector: '#t-toast',
        message: this.privateData.verifyTips,
        icon: '',
        duration: 1000,
      });
      return
    }
    this.hasSava = true;
    let tempData = this.data.locationState
    tempData.grade = this.data.gradeValue
    tempData.sex = this.data.sexValue
    tempData.height = this.data.heightValue
    tempData.weight = this.data.weightValue
    tempData.i_id = this.data.schoolId
    tempData.class = this.data.classValue
    resolveStudents(tempData);


    // clearStudentsPromise()
  },
  getSplitGradeClass(cfg) {
    var tempList = []
    var gradeCount = cfg.split('|')
    for (let index = 0; index < gradeCount.length; index++) {
      let classes = gradeCount[index].split('_')
      this.privateData.gradeMap[classes[0]] = []
      tempList.push({ label: this.getGradeDesc(classes[0]), value: classes[0] })
      this.privateData.gradeDescMap[this.getGradeDesc(classes[0])] = classes[0]
      for (let i = 1; i < classes.length; i++) {
        this.privateData.gradeMap[classes[0]].push(classes[i])
      }
    }
    return tempList
  },
  getClassDesc(grade) {
    var tempList = this.privateData.gradeMap[grade]
    var resultList = []
    for (let index = 0; index < tempList.length; index++) {
      resultList.push({ label: tempList[index], value: tempList[index] })
    }
    return resultList
  },

});
